<template>
  <div style="margin-top:0">
    <!--订单执行-->
    <div class="data-title">
        <div class="title-left">
           <div class="title-item" :class="{'choose':listQuery1.tab == 'my'}" v-if="salePersonalExecuteAnalysis" @click="changeTab1('my')">个人订单执行</div>
           <div class="title-item" :class="{'choose':listQuery1.tab == 'group'}" v-if="saleDivisionExecuteAnalysis" @click="changeTab1('group')">事业部订单执行</div>
           <div class="title-item" :class="{'choose':listQuery1.tab == 'department'}" v-if="saleDepartmentExecuteAnalysis" @click="changeTab1('department')">部门订单执行</div>
           <div class="title-item" :class="{'choose':listQuery1.tab == 'all'}"  v-if="saleAllExecuteAnalysis" @click="changeTab1('all')">公司订单执行</div>
        </div>
        <div class="title-right">
            <el-date-picker
              @change="handleSearchList1"
              style="width:210px;margin-right: 10px;"
              size="small"
              value-format="yyyy-MM-dd"
              v-model="listQuery1.date"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
            <el-cascader
              @change="handleSearchList1"
              v-if="listQuery1.tab != 'my'"
              size="mini"
              collapse-tags
              :show-all-levels="false"
              v-model="listQuery1.userIds"
              placeholder="请选择部门/事业部/人员"
              :options="userList"
              :props="props"></el-cascader>

        </div>
     </div>
    <div class="order-block">
        <div class="data-block order-num" style="height:438px;">
          <div class="order-num-item">
             <div class="num-item-top">待首次确认 <i class="el-icon-caret-right"></i></div>
             <div class="num-item-bottom" @click="topage('waitFirstCheckCount')">
                <div class="bottom-icon"><img src="https://pic.moresu.com/FjGhxrEJsXfVjgN66qzy7fY4AKO5"/></div>
                <div class="bottom-num">{{ waitFirstCheckCount }}<span class="span">单</span></div>
             </div>
          </div>

          <div class="order-num-item">
            <div class="num-item-top">待二次确认 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('waitReCheckCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FjGhxrEJsXfVjgN66qzy7fY4AKO5"/></div>
              <div class="bottom-num">{{ waitReCheckCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item yellow">
            <div class="num-item-top">未审核 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('waitFinanceCheckCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/Fu1MP3xhaYhUXj-rySRK_GJCthvR"/></div>
              <div class="bottom-num">{{ waitFinanceCheckCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item yellow">
            <div class="num-item-top">已审核未排货 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('waitPlanGoodsCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FuLR2Uu_Jwsl5LtQ0RLuTZR9vRtG"/></div>
              <div class="bottom-num">{{ waitPlanGoodsCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item yellow">
            <div class="num-item-top">已排未出库 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('waitShipGoodsCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FuLR2Uu_Jwsl5LtQ0RLuTZR9vRtG"/></div>
              <div class="bottom-num">{{ waitShipGoodsCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item">
            <div class="num-item-top">部分出库 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('partShipGoodsCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/Fmf-qLvM-VTfkrcNoo1j6ES8TwCp"/></div>
              <div class="bottom-num">{{ partShipGoodsCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item gary">
            <div class="num-item-top">已取消 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('cancelOrderCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/Fs03UdclnZ1gsxgfMtJ-bs0TnVXc"/></div>
              <div class="bottom-num">{{ cancelOrderCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item yellow">
            <div class="num-item-top">合同未上传 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('waitUploadContractCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FsKGTVwJF2nh8zWAzRjSW1VariVe"/></div>
              <div class="bottom-num">{{ waitUploadContractCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item yellow">
            <div class="num-item-top">未收货确认 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('waitConfirmReceiptCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FsKGTVwJF2nh8zWAzRjSW1VariVe"/></div>
              <div class="bottom-num">{{ waitConfirmReceiptCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item">
            <div class="num-item-top">未付款 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('waitPayCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FgW3h2P1YY9f6oQfhrJ3SxmzWxCM"/></div>
              <div class="bottom-num">{{ waitPayCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item">
            <div class="num-item-top">未付清 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('partPayCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FgW3h2P1YY9f6oQfhrJ3SxmzWxCM"/></div>
              <div class="bottom-num">{{ partPayCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item red">
            <div class="num-item-top">支付逾期 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('unPayOutTimeCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FvHZDRevhdYJKzCpUwNCthOIgutR"/></div>
              <div class="bottom-num">{{ unPayOutTimeCount }}<span class="span">单</span></div>
            </div>
          </div>


          <div class="order-num-item">
            <div class="num-item-top">开票完成 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('finishedInvoiceCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FgW3h2P1YY9f6oQfhrJ3SxmzWxCM"/></div>
              <div class="bottom-num">{{ finishedInvoiceCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item">
            <div class="num-item-top">部分开票 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('hasInvoiceCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FgW3h2P1YY9f6oQfhrJ3SxmzWxCM"/></div>
              <div class="bottom-num">{{ hasInvoiceCount }}<span class="span">单</span></div>
            </div>
          </div>

          <div class="order-num-item red">
            <div class="num-item-top">未开票 <i class="el-icon-caret-right"></i></div>
            <div class="num-item-bottom" @click="topage('unInvoiceCount')">
              <div class="bottom-icon"><img src="https://pic.moresu.com/FvHZDRevhdYJKzCpUwNCthOIgutR"/></div>
              <div class="bottom-num">{{ unInvoiceCount }}<span class="span">单</span></div>
            </div>
          </div>


        </div>
        <div class="data-block order-table" style="height:438px;">
          <el-table :data="list1"  style="width: 100%;" class="data-table" :height="412" v-loading="listLoading1">
            <el-table-column
              align="center"
              label="销售员"
              min-width="100">
              <template slot-scope="scope">{{scope.row.userRealName}}</template>
            </el-table-column>
            <el-table-column
              align="center"
              label="待确认"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.waitFirstCheckCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="二次确认"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.waitReCheckCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="未审核"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.waitFinanceCheckCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="已审核未排货"
              min-width="150">
              <template slot-scope="scope">
                {{scope.row.waitPlanGoodsCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="已排未出库"
              min-width="100">
              <template slot-scope="scope">
               {{scope.row.waitShipGoodsCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="部分出库"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.partShipGoodsCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="已取消"
              min-width="100">
              <template slot-scope="scope">
               {{scope.row.cancelOrderCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="合同未上传"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.waitUploadContractCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="未收货确认"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.waitUploadContractCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="未付款"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.waitPayCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="未付清"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.partPayCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="支付逾期"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.unPayOutTimeCount}}
              </template>
            </el-table-column>
          </el-table>
        </div>
    </div>

    <!--销售情况&目标-->
    <el-row style="margin-top:10px" :gutter="8">
      <el-col :span="12">
        <div class="data-title">
          <div class="title-left">
            <div class="title-item" :class="{'choose':listQuery2.tab == 'my'}" v-if="salePersonalOrderAnalysis" @click="changeTab2('my')">销售-个人销量</div>
            <div class="title-item" :class="{'choose':listQuery2.tab == 'group'}" v-if="saleDivisionOrderAnalysis" @click="changeTab2('group')">销售-事业部销量</div>
            <div class="title-item" :class="{'choose':listQuery2.tab == 'department'}" v-if="saleDepartmentOrderAnalysis" @click="changeTab2('department')">销售-部门销量</div>
            <div class="title-item" :class="{'choose':listQuery2.tab == 'all'}"  v-if="saleAllOrderAnalysis" @click="changeTab2('all')">销售-公司销量</div>
          </div>
          <div class="title-right">
            <el-cascader
              @change="getSaleSum"
              v-if="listQuery2.tab !='my'"
              size="mini"
              collapse-tags
              :show-all-levels="false"
              v-model="listQuery2.userIds"
              placeholder="请选择部门/事业部/人员"
              :options="userList"
              :props="props"></el-cascader>

          </div>
        </div>
        <div class="sum-block" >
           <el-row :gutter="5" v-if="saleSum">
             <el-col :span="6">
               <div class="sum-block-item">
                  <div class="sum-title" style="height: auto;line-height: 30px;padding: 10px 0;position: relative">
                    <div>日统计</div>
                    <div style="position: absolute;right:16px;font-size: 12px;font-weight: 500;color:#666;top:42px;z-index: 2">日</div>
                    <el-date-picker
                      :clearable="false"
                      style="width:90%;"
                      size="mini"
                      v-model="thisDay"
                      @change="(value) => handleChangeTime(value, 'today')"
                      type="date"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      placeholder="选择日期">
                    </el-date-picker>
                  </div>
                 <div  class="sum-con">
                   <div class="sum-con-div">
                     <div class="label">订单</div>
                     <div class="num">{{ saleSum.todayOrderNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">出库</div>
                     <div class="num">{{ saleSum.todayShipNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">毛利</div>
                     <div class="num">{{ saleSum.todayShipProfit }}<span class="unit">元</span></div>
                   </div>
                 </div>
               </div>
             </el-col>
             <el-col :span="6">
               <div class="sum-block-item">
                 <div class="sum-title" style="height: auto;line-height: 30px;padding: 10px 0;position: relative">
                   <div>周统计</div>
                   <div style="position: absolute;right:16px;font-size: 12px;font-weight: 500;color:#666;top:42px;z-index: 2">周</div>
                   <el-date-picker
                     :clearable="false"
                     style="width:90%;position: relative;z-index: 1"
                     size="mini"
                     @change="(value) => handleChangeTime(value, 'week')"
                     v-model="thisWeekValue"
                     type="week"
                     format="yyyy-WW"
                     placeholder="选择周">
                   </el-date-picker>
                 </div>
                 <div  class="sum-con">
                   <div class="sum-con-div">
                     <div class="label">订单</div>
                     <div class="num">{{ saleSum.weekOrderNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">出库</div>
                     <div class="num">{{ saleSum.weekShipNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">毛利</div>
                     <div class="num">{{ saleSum.weekShipProfit }}<span class="unit">元</span></div>
                   </div>
                 </div>
               </div>
             </el-col>
             <el-col :span="6">
               <div class="sum-block-item">
                 <div class="sum-title" style="height: auto;line-height: 30px;padding: 10px 0;position: relative">
                   <div>月统计</div>
                   <div style="position: absolute;right:16px;font-size: 12px;font-weight: 500;color:#666;top:42px;z-index: 2">月</div>
                   <el-date-picker
                     :clearable="false"
                     style="width:90%;"
                     size="mini"
                     @change="(value) => handleChangeTime(value, 'month')"
                     v-model="thisMonth"
                     type="month"
                     value-format="yyyy-MM"
                     placeholder="选择月">
                   </el-date-picker>
                 </div>
                 <div  class="sum-con">
                   <div class="sum-con-div">
                     <div class="label">订单</div>
                     <div class="num">{{ saleSum.monthOrderNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">出库</div>
                     <div class="num">{{ saleSum.monthShipNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">毛利</div>
                     <div class="num">{{ saleSum.monthShipProfit }}<span class="unit">元</span></div>
                   </div>
                 </div>
               </div>
             </el-col>
             <el-col :span="6">
               <div class="sum-block-item">
                 <div class="sum-title" style="height: auto;line-height: 30px;padding: 10px 0;position: relative">
                   <div>年统计</div>
                   <div style="position: absolute;right:16px;font-size: 12px;font-weight: 500;color:#666;top:42px;z-index: 2">年</div>
                   <el-date-picker
                     :clearable="false"
                     style="width:90%;"
                     size="mini"
                     @change="(value) => handleChangeTime(value, 'year')"
                     v-model="thisYear"
                     type="year"
                     value-format="yyyy"
                     placeholder="选择年">
                   </el-date-picker>
                 </div>
                 <div  class="sum-con">
                   <div class="sum-con-div">
                     <div class="label">订单</div>
                     <div class="num">{{ saleSum.yearOrderNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">出库</div>
                     <div class="num">{{ saleSum.yearShipNum }}<span class="unit">吨</span></div>
                   </div>
                   <div class="sum-con-div">
                     <div class="label">毛利</div>
                     <div class="num">{{ saleSum.yearShipProfit }}<span class="unit">元</span></div>
                   </div>
                 </div>
               </div>
             </el-col>

           </el-row>
        </div>
      </el-col>

      <el-col :span="12">
        <div class="data-title">
          <div class="title-left">
            <div class="title-item" :class="{'choose':listQuery3.tab == 'my'}" v-if="salePersonalTargetAnalysis" @click="changeTab3('my')">销售-个人目标达成</div>
            <div class="title-item" :class="{'choose':listQuery3.tab == 'group'}" v-if="saleDivisionTargetAnalysis" @click="changeTab3('group')">销售-事业部目标达成</div>
            <div class="title-item" :class="{'choose':listQuery3.tab == 'department'}" v-if="saleDepartmentTargetAnalysis" @click="changeTab3('department')">销售-部门目标达成</div>
            <div class="title-item" :class="{'choose':listQuery3.tab == 'all'}"  v-if="saleAllTargetAnalysis" @click="changeTab3('all')">销售-公司目标达成</div>
          </div>
          <div class="title-right">
            <el-cascader
              @change="getSaleTarget"
              v-if="listQuery3.tab != 'my'"
              size="mini"
              collapse-tags
              :show-all-levels="false"
              v-model="listQuery3.userIds"
              placeholder="请选择部门/事业部/人员"
              :options="userList"
              :props="props"></el-cascader>

          </div>
        </div>
        <div class="target-block" v-if="saleTarget">
          <el-row :gutter="5" >
             <el-col :span="12">
                <div class="target-item" style="padding:19px 12px">
                  <div class="target-left">
                     <div class="target-label">本月销量目标</div>
                     <div class="target-num">{{ saleTarget.monthOrderNumTarget}}<span class="unit">吨</span></div>
                     <div class="target-differ" :class="{'green':saleTarget.monthOrderNumDiff >= 0,'red':saleTarget.monthOrderNumDiff < 0}">目标差额<span class="unit">{{saleTarget.monthOrderNumDiff<0 ? '↓ ':'↑ '}}{{Math.abs(saleTarget.monthOrderNumDiff)}}吨</span></div>
                  </div>
                  <div class="target-right">
                    <el-progress type="circle" :percentage="saleTarget.monthOrderNumDiffRate" :width="88" color="#00b8f2" :format="formatProgress"></el-progress>
                  </div>
                </div>
             </el-col>
             <el-col :span="12">
              <div class="target-item purple" style="padding:19px 12px">
                <div class="target-left">
                  <div class="target-label">本月毛利目标</div>
                  <div class="target-num">{{ saleTarget.monthShipProfitTarget }}<span class="unit">元</span></div>
                  <div class="target-differ" :class="{'green':saleTarget.monthShipProfitDiff >= 0,'red':saleTarget.monthShipProfitDiff < 0}">目标差额<span class="unit">{{saleTarget.monthShipProfitDiff<0 ? '↓ ':'↑ '}}{{ Math.abs(saleTarget.monthShipProfitDiff) }}元</span></div>
                </div>
                <div class="target-right">
                  <el-progress type="circle" :percentage="saleTarget.monthShipProfitDiffRate" :width="88" color="#8252e9"></el-progress>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="5" style="margin-top: 8px">
            <el-col :span="12">
              <div class="target-item bule" style="padding:19px 12px">
                <div class="target-left">
                  <div class="target-label">本年销量目标</div>
                  <div class="target-num">{{ saleTarget.yearOrderNumTarget }}<span class="unit">吨</span></div>
                  <div class="target-differ" :class="{'green':saleTarget.yearOrderNumDiff >= 0,'red':saleTarget.yearOrderNumDiff < 0}">目标差额<span class="unit">{{saleTarget.yearOrderNumDiff<0 ? '↓ ':'↑ '}}{{Math.abs(saleTarget.yearOrderNumDiff)}}吨</span></div>
                </div>
                <div class="target-right">
                  <el-progress type="circle" :percentage="saleTarget.yearOrderNumDiffRate" :width="88" color="#3860f2"></el-progress>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="target-item green" style="padding:19px 12px">
                <div class="target-left">
                  <div class="target-label">本年毛利目标</div>
                  <div class="target-num">{{ saleTarget.yearShipProfitTarget }}<span class="unit">元</span></div>
                  <div class="target-differ" :class="{'green':saleTarget.yearShipProfitDiff >= 0,'red':saleTarget.yearShipProfitDiff < 0}">目标差额<span class="unit">{{saleTarget.yearShipProfitDiff<=0 ? '↓ ':'↑ '}}{{ Math.abs(saleTarget.yearShipProfitDiff) }}元</span></div>
                </div>
                <div class="target-right">
                  <el-progress type="circle" :percentage="saleTarget.yearShipProfitDiffRate" :width="88" color="#45b369"></el-progress>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>

    </el-row>

    <!--人员销售*人员毛利*品类销售-->
    <div class="data-title" style="margin-top: 10px">
      <div class="title-left">
        <div class="title-item" :class="{'choose':curIndex4 ==1}" @click="changeTab4(1)" v-if="saleOrderTargetAnalysis">销售-人员销量</div>
        <div class="title-item" :class="{'choose':curIndex4 ==2}" @click="changeTab4(2)" v-if="saleShipTargetAnalysis">销售-人员毛利</div>
        <div class="title-item" :class="{'choose':curIndex4 ==3}" @click="changeTab4(3)">销售-品类销量</div>
        <div class="title-item" :class="{'choose':curIndex4 ==4}" @click="changeTab4(4)">销售-品类毛利</div>
      </div>
      <div class="title-right">
        <el-radio-group v-model="radio" size="mini" style="margin-right: 10px" v-if="curIndex4 == 2 || curIndex4 == 4" @change="getChartsData">
          <el-radio-button label="1">吨毛利</el-radio-button>
          <el-radio-button label="2">总毛利</el-radio-button>
        </el-radio-group>
        <el-date-picker
          @change="getChartsData"
          style="width:150px;margin-right: 10px"
          size="mini"
          value-format="yyyy-MM"
          placeholder="请选择月份"
          v-model="listQuery4.month"
          type="month"
          align="right">
        </el-date-picker>
        <el-select @change="getChartsData" size="mini" placeholder="请选择品类" clearable style="margin-right: 10px;width:150px" v-if="curIndex4 != 3 && curIndex4 != 4" v-model="listQuery4.goodsClass" >
          <el-option v-for="item in classList" :key="item.classId" :value="item.className" :label="item.className"></el-option>
        </el-select>
        <el-input size="mini" @change="getChartsData" placeholder="请输入厂家" clearable style="width:150px;margin-right: 10px" v-if="curIndex4 != 3 && curIndex4 != 4 && listQuery4.goodsClass" v-model="listQuery4.brandName"></el-input>
        <el-cascader
          @change="getChartsData"
          size="mini"
          collapse-tags
          :show-all-levels="false"
          v-model="listQuery4.userIds"
          placeholder="请选择部门/事业部/人员"
          :options="userList"
          :props="props"></el-cascader>

      </div>
    </div>
    <div class="data-block" style="margin-top: 10px">
      <div id="myChart" style="height: 300px" class="charts-div" v-loading="chartLoading"></div>
    </div>


  </div>
</template>

<script>
import {saleOrderExeAnalysis,saleOrderExeAnalysisList,saleOrderSummary,saleTargetSummary,userOrderNumAnalysis,
  userProfitAnalysis,userPerProfitAnalysis,classOrderNumAnalysis,classProfitAnalysis,classPerProfitAnalysis} from '@/api/data.js'
import echarts from "echarts";
import {formatDate} from '@/utils/date';
import store from '@/store';
import {mapGetters} from "vuex";
import moment from "moment";
const defaultListQuery={
  date : [],
  tab: "" ,  //我的：my  部门:department  事业部:group  公司：all
  userIds:[],
};

const defaultListQuery2={
  tab: "" ,  //我的：my  部门:department  事业部:group  公司：all
  userIds:[],
};

const defaultListQuery3={
  tab: "" ,  //我的：my  部门:department  事业部:group  公司：all
  userIds:[],
};

const defaultListQuery4={
  "userIds"   : [],   //人员ID
  "month" : "",   //统计月份
  "goodsClass" : "", //品类
  "brandName" : "" //厂家
};

  export default {
    name: 'saleData',
    data() {
      return {
        roles:store.getters.roles ? store.getters.roles : [],
        pickerOptions: {
          shortcuts: [{
            text: '今日',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '本周',
            onClick(picker) {
              const now = new Date();
              // 获取今天是本周的第几天（0代表星期日，1代表星期一，...，6代表星期六）
              const dayOfWeek = now.getDay();
              // 计算本周第一天（星期一）的日期
              const startOfWeek = new Date(now);
              startOfWeek.setDate(now.getDate() - dayOfWeek + 1); // 调整为星期一
              // 计算本周最后一天（星期日）的日期
              const endOfWeek = new Date(startOfWeek);
              endOfWeek.setDate(startOfWeek.getDate() + 6); // 从星期一开始加6天得到星期日
              picker.$emit('pick', [startOfWeek, endOfWeek]);
            }
          }, {
            text: '本月',
            onClick(picker) {
              const now = new Date();
              // 获取当前月份和年份
              const month = now.getMonth();
              const year = now.getFullYear();
              // 计算本月第一天的日期
              const startOfMonth = new Date(year, month, 1);
              // 计算下个月第一天的日期，然后减去一天得到本月的最后一天
              const startOfNextMonth = new Date(year, month + 1, 1);
              const endOfMonth = new Date(startOfNextMonth);
              endOfMonth.setDate(startOfNextMonth.getDate() - 1);
              picker.$emit('pick', [startOfMonth, endOfMonth]);
            }
          }, {
            text: '本年',
            onClick(picker) {
              const now = new Date();
              // 获取当前年份
              const year = now.getFullYear();
              // 计算本年第一天的日期（1月1日）
              const startOfYear = new Date(year, 0, 1);
              // 计算本年最后一天的日期（12月31日）
              const endOfYear = new Date(year, 11, 31);
              picker.$emit('pick', [startOfYear, endOfYear]);
            }
          }]
        },
        props:{multiple: true,label:'value',value:'label',emitPath:false},
        list1:[],
        listQuery1: JSON.parse(JSON.stringify(defaultListQuery)),
        count1:0,
        listLoading1:false,
        waitFirstCheckCount:0, //待销售首次确认
        waitReCheckCount :0, //待销售二次确认
        waitFinanceCheckCount :0, //待财务审核
        waitShipGoodsCount :0,//已排货待发货
        partShipGoodsCount:0, //部分出库
        cancelOrderCount :0,//已取消
        waitUploadContractCount :0,//待上传合同
        waitConfirmReceiptCount :0, //待上传收货确认函
        waitPayCount :0,//待付款
        partPayCount :0, //未付清
        unPayOutTimeCount :0,//支付逾期
        waitPlanGoodsCount:0,//已审核未排货
        unInvoiceCount:0,   //未开票订单数
        hasInvoiceCount:0,  //部分开票订单数
        finishedInvoiceCount:0,  //开票完成订单数



        listQuery2: JSON.parse(JSON.stringify(defaultListQuery2)),
        saleSum:null,

        listQuery3: JSON.parse(JSON.stringify(defaultListQuery3)),
        saleTarget:null,

        listQuery4: JSON.parse(JSON.stringify(defaultListQuery4)),
        curIndex4:1,
        resizeObserver:null,
        myChart:null,
        radio:'1',
        xKey:"",
        targetName:"",
        actualName:"",
        completionName:"",
        chartLoading:false,
        averageName:null,
        thisDay:'',
        thisWeekValue:'',
        thisMonth:'',
        thisYear:'',
      }
    },
    props: {
      userList: {
        type: Array,
        default: () => []
      },
      classList:{
        type: Array,
        default: () => []
      }
    },
    filters: {



    },
    created(){
      if(this.salePersonalExecuteAnalysis){
        this.listQuery1.tab = 'my'
      }else if(this.saleDivisionExecuteAnalysis){
        this.listQuery1.tab = 'group'
      }else if(this.saleDepartmentExecuteAnalysis){
        this.listQuery1.tab = 'department'
      }else if(this.saleAllExecuteAnalysis){
        this.listQuery1.tab = 'all'
      }
      if(this.salePersonalOrderAnalysis){
        this.listQuery2.tab = 'my'
      }else if(this.saleDivisionOrderAnalysis){
        this.listQuery2.tab = 'group'
      }else if(this.saleDepartmentOrderAnalysis){
        this.listQuery2.tab = 'department'
      }else if(this.saleAllOrderAnalysis){
        this.listQuery2.tab = 'all'
      }

      if(this.salePersonalTargetAnalysis){
        this.listQuery3.tab = 'my'
      }else if(this.saleDivisionTargetAnalysis){
        this.listQuery3.tab = 'group'
      }else if(this.saleDepartmentTargetAnalysis){
        this.listQuery3.tab = 'department'
      }else if(this.saleAllTargetAnalysis){
        this.listQuery3.tab = 'all'
      }

      if(this.saleOrderTargetAnalysis){
        this.curIndex4 = 1
      }else if(this.saleShipTargetAnalysis){
        this.curIndex4 = 2
      }else {
        this.curIndex4 = 3
      }

      this.listQuery1.date = this.getMonth()
      this.listQuery4.month = formatDate(new Date(), 'yyyy-MM')
      // console.log(this.listQuery2)

      this.thisDay = formatDate(new Date(), 'yyyy-MM-dd')
      this.thisWeekValue = new Date();
      this.thisMonth = formatDate(new Date(), 'yyyy-MM')
      this.thisYear = formatDate(new Date(), 'yyyy')
      this.getList1();
      this.getOrderNum();
      this.getSaleSum()
      this.getSaleTarget()
      this.$nextTick(()=>{
        this.getChartsData()
        // 智能响应式方案
        const elements = document.querySelectorAll('.charts-div');
        this.resizeObserver = new ResizeObserver(entries => {
          entries.forEach(entry => {
            if(entry.target.id == 'myChart'){
              this.myChart.resize({
                animation: { duration: 300 }, // 启用平滑过渡
                throttle: 200 // 节流控制
              });
            }
          })
        });
        elements.forEach(el => {
          this.resizeObserver.observe(el);
        });
      })

    },

    beforeDestroy() {
      if (this.resizeObserver) {
        const elements = document.querySelectorAll('.charts-div');
        elements.forEach(el => {
          this.resizeObserver.unobserve(el);
        });
        this.resizeObserver.disconnect();
        this.myChart.dispose();
      }
    },
    components:{

    },
    computed:{
      salePersonalExecuteAnalysis() { //个人订单执行情况
        if(this.roles.indexOf("salePersonalExecuteAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      saleDivisionExecuteAnalysis() { //事业部订单执行情况
        if(this.roles.indexOf("saleDivisionExecuteAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      saleDepartmentExecuteAnalysis() { //部门订单执行情况
        if(this.roles.indexOf("saleDepartmentExecuteAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      saleAllExecuteAnalysis() { //公司订单执行情况
        if(this.roles.indexOf("saleAllExecuteAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      salePersonalOrderAnalysis() { //个人销售执行情况
        if(this.roles.indexOf("salePersonalOrderAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      saleDivisionOrderAnalysis() { //事业部销售情况
        if(this.roles.indexOf("saleDivisionOrderAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      saleDepartmentOrderAnalysis() { //部门销售情况
        if(this.roles.indexOf("saleDepartmentOrderAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      saleAllOrderAnalysis() { //公司销售情况
        if(this.roles.indexOf("saleAllOrderAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      salePersonalTargetAnalysis() { //个人目标达成
        if(this.roles.indexOf("salePersonalTargetAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      saleDivisionTargetAnalysis() { //事业部目标达成
        if(this.roles.indexOf("saleDivisionTargetAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      saleDepartmentTargetAnalysis() { //部门目标达成
        if(this.roles.indexOf("saleDepartmentTargetAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      saleAllTargetAnalysis() { //公司目标达成
        if(this.roles.indexOf("saleAllTargetAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      saleOrderTargetAnalysis() { //人员销售情况
        if(this.roles.indexOf("saleOrderTargetAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      saleShipTargetAnalysis() { //人员毛利情况
        if(this.roles.indexOf("saleShipTargetAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
    },
    methods: {
      handleChangeTime(value,type){
        if(value){
          let listQuery2 = JSON.parse(JSON.stringify(this.listQuery2));
          if(type == 'today'){
            listQuery2.thisDay = this.thisDay
          }else if(type == 'week'){
            const start = new Date(value.getTime());
            start.setDate(start.getDate()-1); // 设置周起始日为周一
            const end = new Date(start);
            end.setDate(end.getDate() + 6); // 设置周结束日为周日
            listQuery2.thisWeek = [formatDate(start, 'yyyy-MM-dd'),formatDate(end, 'yyyy-MM-dd')]
          }else if(type == 'month'){
            listQuery2.thisMonth = this.thisMonth
          }else if(type == 'year'){
            listQuery2.thisYear = this.thisYear
          }
          saleOrderSummary(listQuery2).then((res)=>{
            let OrderNum = type+'OrderNum'
            let ShipNum = type+'ShipNum'
            let ShipProfit = type+'ShipProfit'
            this.saleSum[OrderNum] = res[OrderNum]
            this.saleSum[ShipNum] = res[ShipNum]
            this.saleSum[ShipProfit] = res[ShipProfit]
          })
        }
      },
      formatProgress(percentage){
        return `${percentage}%`
      },
      topage(type,params){
        let routeData
        switch (type){
          case 'waitFirstCheckCount' :
             routeData = this.$router.resolve({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataOrderState:'0'}});
            // this.$router.push({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataOrderState:'0'}});
            break;
          case 'waitReCheckCount' :
             routeData = this.$router.resolve({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataOrderState:'30'}});
            // this.$router.push({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataOrderState:'30'}});
            break;
          case 'waitFinanceCheckCount':
            routeData = this.$router.resolve({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataFinanceState:'0'}});
            // this.$router.push({name:'saleContractDetails',query:{dataDate:this.listQuery1.date,dataFinanceState:'0'}});
            break;
          case 'waitPlanGoodsCount':
            routeData = this.$router.resolve({name:'saleContractDetails',query:{dataSendType:'unPlan',dataDate:this.listQuery1.date,dataFinanceState:['1','3'].join(",")}});
            // this.$router.push({name:'saleContractDetails',query:{dataSendType:'unPlan',dataDate:this.listQuery1.date}});
            break;
          case 'waitShipGoodsCount':
            routeData = this.$router.resolve({name:'saleContractDetails',query:{dataSendType:'yap',dataPlanState:'30',dataDate:this.listQuery1.date}});
            // this.$router.push({name:'saleContractDetails',query:{dataSendType:'yap'}});
            break;
          case 'partShipGoodsCount':
            routeData = this.$router.resolve({name:'saleContractDetails',query:{dataSendType:'yap',dataDate:this.listQuery1.date}});
            // this.$router.push({name:'saleContractDetails',query:{dataSendType:'yap'}});
            break;
          case 'cancelOrderCount':
            routeData = this.$router.resolve({name:'sale',query:{dataTab:this.listQuery1.tab,dataOrderState:'10',dataDate:this.listQuery1.date}});
            // this.$router.push({name:'saleContractDetails',query:{dataOrderState:'10',dataDate:this.listQuery1.date}});
            break;
          case 'waitUploadContractCount':
            routeData = this.$router.resolve({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataHasUploadContract:'0'}});
            // this.$router.push({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataHasUploadContract:'0'}});
            break;
          case 'waitConfirmReceiptCount':
            routeData = this.$router.resolve({name:'saleDeliverConfirm',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataPrintStatus:'0'}});
            // this.$router.push({name:'saleDeliverConfirm',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataPrintStatus:'0'}});
            break;
          case 'waitPayCount':
            routeData = this.$router.resolve({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataPayState:'0'}});
            // this.$router.push({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataPayState:'0'}});
            break;
          case 'partPayCount':
            routeData = this.$router.resolve({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataPayState:'1'}});
            // this.$router.push({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataPayState:'1'}});
            break;
          case 'unPayOutTimeCount':
            routeData = this.$router.resolve({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataNeedPayOutTime:'1'}});
            // this.$router.push({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataNeedPayOutTime:'1'}});
            break;
          case 'userSaleNumAnalysis':
            routeData = this.$router.resolve({name:type,query:{dataMonth:this.listQuery4.month,dataGoodsClass:this.listQuery4.goodsClass,dataBrandName:this.listQuery4.brandName,dataUserIds:this.listQuery4.userIds.join(',')}});
            // this.$router.push({name:type,query:{dataMonth:this.listQuery4.month,dataGoodsClass:this.listQuery4.goodsClass,dataBrandName:this.listQuery4.brandName,dataUserIds:this.listQuery4.userIds.join(',')}});
            break;
          case 'goodsSaleNumAnalysis':
            routeData = this.$router.resolve({name:type,query:{dataMonth:this.listQuery4.month,dataGoodsClass:params,dataUserIds:this.listQuery4.userIds.join(',')}});
            // this.$router.push({name:type,query:{dataMonth:this.listQuery4.month,dataGoodsClass:params,dataUserIds:this.listQuery4.userIds.join(',')}});
            break;
          case 'unInvoiceCount':
            routeData = this.$router.resolve({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataInvoiceState:'0',dataOrderState:'40'}});
            // this.$router.push({name:type,query:{dataMonth:this.listQuery4.month,dataGoodsClass:params,dataUserIds:this.listQuery4.userIds.join(',')}});
            break;
          case 'hasInvoiceCount':
            routeData = this.$router.resolve({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataInvoiceState:'1',dataOrderState:'40'}});
            // this.$router.push({name:type,query:{dataMonth:this.listQuery4.month,dataGoodsClass:params,dataUserIds:this.listQuery4.userIds.join(',')}});
            break;
          case 'finishedInvoiceCount':
            routeData = this.$router.resolve({name:'sale',query:{dataTab:this.listQuery1.tab,dataDate:this.listQuery1.date,dataInvoiceState:'2',dataOrderState:'40'}});
            // this.$router.push({name:type,query:{dataMonth:this.listQuery4.month,dataGoodsClass:params,dataUserIds:this.listQuery4.userIds.join(',')}});
            break;
        }
        window.open(routeData.href);
      },
      changeTab4(index){
        this.curIndex4 = index
        this.listQuery4 = JSON.parse(JSON.stringify(defaultListQuery4))
        this.listQuery4.month = formatDate(new Date(), 'yyyy-MM')
        this.radio = '1'
        this.myChart.clear()
        this.getChartsData()
      },
      //获取图表数据
      getChartsData(){
        let fn
        this.listQuery4.brandName = this.listQuery4.goodsClass ? this.listQuery4.brandName : ''
        let listQuery4 = JSON.parse(JSON.stringify(this.listQuery4))
        listQuery4.userIds = listQuery4.userIds.join(",")
        this.chartLoading = true
        if(this.curIndex4 == 1){
          fn = userOrderNumAnalysis
          this.xKey = "userRealName"
          this.targetName = "orderNumTarget"
          this.actualName = "orderNumActual"
          this.completionName = "orderNumDiffRate"
          this.averageName = null
        }else if(this.curIndex4 == 2 && this.radio == 1){
          this.xKey = "userRealName"
          this.targetName = null
          this.actualName = "perShipProfitActual"
          this.averageName = 'averagePerProfit'
          this.completionName = null
          fn = userPerProfitAnalysis
        }else if(this.curIndex4 == 2 && this.radio == 2){
            this.xKey = "userRealName"
            this.targetName = null
            this.actualName = "shipProfitActual"
            this.averageName = 'averageProfit'
            this.completionName = null
            fn = userProfitAnalysis
        }else if(this.curIndex4 == 4 && this.radio == 1){
          this.xKey = "className"
          this.targetName = null
          this.actualName = "shipPerProfitActual"
          this.completionName = null
          this.averageName = null
          delete listQuery4.goodsClass
          delete listQuery4.brandName
          fn = classPerProfitAnalysis
        }else if(this.curIndex4 == 4 && this.radio == 2){
          this.xKey = "className"
          this.targetName = null
          this.actualName = "shipProfitActual"
          this.completionName = null
          this.averageName = null
          fn = classProfitAnalysis
          delete listQuery4.goodsClass
          delete listQuery4.brandName
        }else if(this.curIndex4 == 3){
          this.xKey = "className"
          this.targetName = "orderNumTarget"
          this.actualName = "orderNumActual"
          this.completionName = "orderNumDiffRate"
          this.averageName = null
          fn = classOrderNumAnalysis
          delete listQuery4.goodsClass
          delete listQuery4.brandName
        }

        fn(listQuery4).then((res)=>{
          this.chartLoading = false
          if(this.curIndex4 == 1 || this.curIndex4 == 3){
            this.drawCharts(res)
          }else{
            this.drawCharts2(res)
          }

        })
      },
      changeTab3(tab){
        this.listQuery3 = JSON.parse(JSON.stringify(defaultListQuery3))
        this.listQuery3.tab = tab
        this.getSaleTarget()
      },
      //获取销售目标达成
      getSaleTarget(){
        let listQuery3 = JSON.parse(JSON.stringify(this.listQuery3));
        listQuery3.userIds = listQuery3.userIds.join(",")
        saleTargetSummary(listQuery3).then((res)=>{
          this.saleTarget = res
        })
      },

      changeTab2(tab){
        this.listQuery2 = JSON.parse(JSON.stringify(defaultListQuery2))
        this.listQuery2.tab = tab
        this.getSaleSum()
      },
      //获取销售情况统计
      getSaleSum(){
        let listQuery2 = JSON.parse(JSON.stringify(this.listQuery2));
        listQuery2.userIds = listQuery2.userIds.join(",")
        saleOrderSummary(listQuery2).then((res)=>{
            this.saleSum = res
        })
      },
       //获取本月时间
      getMonth(){
        const now = new Date();
        // 获取当前月份和年份
        const month = now.getMonth();
        const year = now.getFullYear();
        // 计算本月第一天的日期
        const startOfMonth = new Date(year, month, 1);
        // 计算下个月第一天的日期，然后减去一天得到本月的最后一天
        const startOfNextMonth = new Date(year, month + 1, 1);
        const endOfMonth = new Date(startOfNextMonth);
        endOfMonth.setDate(startOfNextMonth.getDate() - 1);
        return [formatDate(new Date(startOfMonth), 'yyyy-MM-dd'),formatDate(new Date(endOfMonth), 'yyyy-MM-dd')]
      },


      //切换订单执行
      changeTab1(tab){
        this.listQuery1 = JSON.parse(JSON.stringify(defaultListQuery))
        this.listQuery1.tab = tab
        this.listQuery1.date = this.getMonth()
        this.handleSearchList1()
      },


      handleSearchList1(){
        this.getList1();
        this.getOrderNum()
      },

      //获取订单执行情况
      getList1() {
        this.listLoading1 = true;
        let listQuery = JSON.parse(JSON.stringify(this.listQuery1));
        listQuery.userIds = listQuery.userIds.join(",")
        saleOrderExeAnalysisList(listQuery).then(response => {
          this.list1 = response.list;
          this.listLoading1 = false;
        }).catch(()=>{
          this.listLoading1 = false;
        });
      },

      //获取订单执行汇总情况
      getOrderNum(){
        let listQuery = JSON.parse(JSON.stringify(this.listQuery1));
        listQuery.userIds = listQuery.userIds.join(",")
        saleOrderExeAnalysis(listQuery).then(response => {
            this.waitFirstCheckCount = response.waitFirstCheckCount //待销售首次确认
            this.waitReCheckCount = response.waitReCheckCount //待销售二次确认
            this.waitFinanceCheckCount = response.waitFinanceCheckCount //待财务审核
            this.waitShipGoodsCount = response.waitShipGoodsCount //已排货待发货
            this.partShipGoodsCount = response.partShipGoodsCount //部分出库
            this.cancelOrderCount = response.cancelOrderCount//已取消
            this.waitUploadContractCount = response.waitUploadContractCount//待上传合同
            this.waitConfirmReceiptCount = response.waitConfirmReceiptCount //待上传收货确认函
            this.waitPayCount = response.waitPayCount//待付款
            this.partPayCount = response.partPayCount //未付清
            this.unPayOutTimeCount = response.unPayOutTimeCount //支付逾期
            this.waitPlanGoodsCount = response.waitPlanGoodsCount
            this.unInvoiceCount = response.unInvoiceCount
            this.hasInvoiceCount = response.hasInvoiceCount
            this.finishedInvoiceCount = response.finishedInvoiceCount
        }).catch(()=>{

        });
      },


      drawCharts(data){
        this.myChart = echarts.init(document.getElementById('myChart'),null,{renderer: 'canvas',useDirtyRect: false});
        // 假设我们有目标销量和实际销量的数据
        let salesData = data

        // 准备数据
        let categories = salesData.map(item => item[this.xKey]);  //x轴
        let targetSales = salesData.map(item => item[this.targetName]);//目标数量
        let actualSales = salesData.map(item => item[this.actualName]);//实际数量
        let differences = salesData.map(item => Number((item[this.actualName] - item[this.targetName]).toFixed(3))*1);//差异值
        let completion = salesData.map(item => item[this.completionName]); //完成率

        // 确定每个项目哪个销量更高
        let isActualHigher = salesData.map(item => item[this.actualName] >= item[this.targetName]);  //是否超过目标

        let higherSalesIndexes = [];
        let lowerSalesValues = [];
        let lineColors = [];
        targetSales.forEach((target, index) => {
          let diff = actualSales[index] - target;
          lineColors.push(diff > 0 ? 'green' : 'red');
          if (actualSales[index] > target) {
            higherSalesIndexes.push(index);
            lowerSalesValues.push(target);
          } else {
            higherSalesIndexes.push(-1); // 标记为无对应高销量
            lowerSalesValues.push(actualSales[index]);
          }
        });
        const minShowItems = 15; // 触发滚动的最小数据量
        let yName,y1Name,y2Name,lineName
        if(this.curIndex4 == 1 || this.curIndex4 == 3){
          yName = '目标销量'
          y1Name = '实际销量'
          y2Name = '销量差额'
          lineName = '销量'
        }else if(this.radio == 1){

          yName = '目标吨毛利'
          y1Name = '实际吨毛利'
          y2Name = '吨毛利差额'
          lineName = '吨毛利'
        }else if(this.radio == 2){
          yName = '目标总毛利'
          y1Name = '实际总毛利'
          y2Name = '总毛利差额'
          lineName = '毛利'
        }

         let option = {
            tooltip: {
              trigger: 'axis',
              backgroundColor:'none',
              formatter: function(params) {
                let diff =Number((params[1].value-params[0].value).toFixed(3))*1
                let color = '#000000'
                if(params[1].value-params[0].value >= 0){
                  diff = '↑ '+Math.abs(diff)+'吨'
                  color = 'green'
                }else{
                  color = 'red'
                  diff = '↓ '+Math.abs(diff)+'吨'
                }
                let html = `<div style="padding:12px 30px 12px 12px;line-height: 26px;background:rgba(255,255,255,0.8);box-shadow: 2px 2px 5px rgba(0,0,0,0.3);border-radius: 8px;border:1px solid #5e83f1">
                  <div style="color:#000;font-size: 16px;font-weight: bold;">${params[0].name}</div>
                  <div style="color:#8b8b8b;font-size: 14px;">${yName}：<span style="color:#6084f2;font-weight: bold">${params[0].value}吨</span></div>
                  <div style="color:#8b8b8b;font-size: 14px;">${y1Name}：<span style="color:#ffc27b;font-weight: bold">${params[1].value}吨</span></div>
                  <div style="color:#8b8b8b;font-size: 14px;">${y2Name}：<span style="color:${color};font-weight: bold">${diff}</span></div>
                  <div style="color:#8b8b8b;font-size: 14px;">完成率：<span style="color:#ef915d;font-weight: bold">${params[2].value}%</span></div>
                  </div>`;
                return html;
              }
            },
            legend: {
              data: [yName, y1Name,'完成率'],
              textStyle: {
                fontSize: 14 // 设置字体大小为16
              },
              orient: 'horizontal',
              x: '50%',        // 水平起点为容器宽度的15%
              y: 20,           // 垂直起点50px
            },
           grid: {
             left: 50,          // 左侧留空比例
             right: 30,          // 右侧留空
             bottom:30,
             top:80,
             containLabel: true,   // 确保标签不被截断
           },
           dataZoom: [
             {
               type: 'slider',      // 滑动条型dataZoom（必须声明）
               height: 10,           // 滚动条高度
               bottom:16,
               show: salesData.length > minShowItems,          // 默认显示
               xAxisIndex: 0,       // 控制第一个xAxis
               zoomLock: true,        // 禁止缩放（仅滚动）
               start: 0,
               end: Math.min(100, (minShowItems / salesData.length) * 100), // 动态计算初始窗口
             }
           ],
            xAxis: {
              type: 'category',
              data: categories,
              axisLine: {
                lineStyle: {
                  color: '#dadada', // X轴轴线颜色
                }
              },
              axisLabel: {
                color: '#818181',       // 字体颜色
                fontSize: 14,        // 字体大小
              },
              axisTick: {
                show: false,          // 显示刻度线
              },
            },
            yAxis: [
              {
                type: 'value',
                name: lineName,
                nameTextStyle:{
                  color:'#898989'
                },
                position: 'left',
                axisLine: {
                  lineStyle: {
                    color: '#dadada', // X轴轴线颜色
                  }
                },
                axisLabel: {
                  color: '#818181',       // 字体颜色
                  fontSize: 10,        // 字体大小
                },
                splitLine: {
                  show: true,                    // 需手动开启
                  lineStyle: {
                    color: '#ebebeb',  // 半透明细线
                    width: 0.5
                  }
                }
              },
              {
                type: 'value',
                name: '完成率',
                nameTextStyle:{
                  color:'#898989'
                },
                position: 'right',
                axisLine: {
                  lineStyle: {
                    color: '#dadada', // X轴轴线颜色
                  }
                },
                axisLabel: {
                  color: '#818181',       // 字体颜色
                  fontSize: 10,        // 字体大小
                },
                splitLine: {
                  show: false,                    // 需手动开启
                }
              },
            ],
            series: [
              {
                name:yName,
                type: 'bar',
                data: targetSales,
                yAxisIndex: 0,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                    { offset: 0, color: '#6084f2' },
                    { offset: 1, color: '#ffffff' }
                  ])
                },
                barWidth:16,
                label: {
                  show: true,
                  position: 'top',
                  color:'red',
                  fontSize:14,
                  offset: [20, 0] ,
                  formatter: function(params) {
                    let diff = differences[params.dataIndex];
                    // 实际比目标小
                    if (!isActualHigher[params.dataIndex]) {
                      return '↓ '+Math.abs(diff)+'吨';
                    }
                    return '';
                  }
                }
              },
              {
                name: y1Name,
                type: 'bar',
                data: actualSales,
                yAxisIndex: 0,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                    { offset: 0, color: '#ffc27b' },
                    { offset: 1, color: '#ffffff' }
                  ])
                },
                barWidth:16,
                label: {
                  show: true,
                  position: 'top',
                  color:'green',
                  fontSize:14,
                  offset: [-14, 0] ,
                  formatter: function(params) {
                    let diff = differences[params.dataIndex];
                    // 实际比目标大
                    if (isActualHigher[params.dataIndex]) {
                      return '↑ '+Math.abs(diff)+'吨';
                    }
                    return '';
                  }
                }
              },
              {
                name: '完成率',
                type: 'line',
                data: completion,
                yAxisIndex: 1,
                lineStyle: {
                  color: '#ee905c',
                  width: 2,
                },
                symbol: 'emptyCircle',       // 顶点形状（circle/diamond/triangle等）
                symbolSize: 8,         // 顶点大小
                itemStyle: {
                  color: '#ee905c',     // 顶点填充色
                  borderColor: '#ee905c',  // 顶点边框色
                  borderWidth: 1        // 边框粗细
                }
              },
              {
                name: '连接线',
                type: 'custom',
                renderItem: function(params, api) {
                  let categoryIndex = params.dataIndex;
                  let startPoint = api.coord([categoryIndex, lowerSalesValues[categoryIndex]]);
                  let endPoint = api.coord([categoryIndex, Math.max(targetSales[categoryIndex], actualSales[categoryIndex])]);
                  let x1,x2
                  if(isActualHigher[categoryIndex] ){
                    x1 = startPoint[0]-10
                    x2 = endPoint[0]-10
                  }else{
                    x1 = startPoint[0]+10
                    x2 = endPoint[0]+10
                  }

                  return {
                    type: 'line',
                    shape: {
                      x1: x1,
                      y1: startPoint[1],
                      x2: x2,
                      y2: endPoint[1]
                    },
                    style: api.style({
                      stroke: lineColors[categoryIndex],
                      lineWidth:1
                    })
                  };

                },
                data: higherSalesIndexes.map((index, i) => [i]) // 使用项目的索引作为数据
              },
              {
                name: '连接线3',
                type: 'custom',
                renderItem: function(params, api) {
                  let categoryIndex = params.dataIndex;
                  let startPoint = api.coord([categoryIndex, lowerSalesValues[categoryIndex]]);
                  let endPoint = api.coord([categoryIndex, Math.max(targetSales[categoryIndex], actualSales[categoryIndex])]);
                  let x1,x2
                  if(isActualHigher[categoryIndex] ){
                    x1 = endPoint[0]+2
                    x2 = endPoint[0]-20
                  }else{
                    x1 = endPoint[0]-2
                    x2 = endPoint[0]+20
                  }

                  return {
                    type: 'line',
                    shape: {
                      x1: x1,
                      y1: endPoint[1],
                      x2: x2,
                      y2: endPoint[1]
                    },
                    style: api.style({
                      stroke: '#888888',
                      lineWidth:1
                    })
                  };

                },
                data: higherSalesIndexes.map((index, i) => [i]) // 使用项目的索引作为数据
              }
            ]
          };
        this.myChart.setOption(option);
        this.myChart.on('click', (params)=> {
          if(this.curIndex4 == 1 || this.curIndex4 == 2){
            this.topage('userSaleNumAnalysis')
          }else{
            // console.log(params)
            this.topage('goodsSaleNumAnalysis',params['name'])
          }

        })
      },

      drawCharts2(data){
        this.myChart = echarts.init(document.getElementById('myChart'),null,{renderer: 'canvas',useDirtyRect: false});
        // 假设我们有目标销量和实际销量的数据
        let salesData = data

        // 准备数据
        let categories = salesData.map(item => item[this.xKey]);  //x轴
        let actualSales = salesData.map(item => item[this.actualName]);//实际数量
        let averageNum = salesData.map(item => item[this.averageName]);//平均值
        averageNum = averageNum[0] ? averageNum[0] : 0
        const minShowItems = 15; // 触发滚动的最小数据量
        let yName,lineName
        if(this.radio == 1){
          yName = '实际吨毛利'
          lineName = '吨毛利'
        }else if(this.radio == 2){
          yName = '实际总毛利'
          lineName = '毛利'
        }
        let markLine = null
        if(this.curIndex4 == 2){
          markLine = {
            data: [{ yAxis:averageNum, name: '平均值' }],
            lineStyle: { color: '#ffbb70', type: 'dashed' }, //
            label: {
                position: 'middle',
                formatter: '{b}: {c}元',
                fontSize: 12,
                color: '#ffbb70',
                show: false,
                triggerOn: 'mouseover',
            },
          }
        }
        let option = {
          tooltip: {
            trigger: 'axis',
            backgroundColor:'none',
            formatter: function(params) {
              let html = `<div style="padding:12px 30px 12px 12px;line-height: 26px;background:rgba(255,255,255,0.8);box-shadow: 2px 2px 5px rgba(0,0,0,0.3);border-radius: 8px;border:1px solid #5e83f1">
                  <div style="color:#000;font-size: 16px;font-weight: bold;">${params[0].name}</div>
                  <div style="color:#8b8b8b;font-size: 14px;">${yName}：<span style="color:#6084f2;font-weight: bold">${params[0].value}元</span></div>
                  </div>`;
              return html;
            }
          },
          legend: {
            data: [yName],
            textStyle: {
              fontSize: 14 // 设置字体大小为16
            },
            orient: 'horizontal',
            x: '50%',        // 水平起点为容器宽度的15%
            y: 20,           // 垂直起点50px
          },
          grid: {
            left: 50,          // 左侧留空比例
            right: 30,          // 右侧留空
            bottom:30,
            top:80,
            containLabel: true,   // 确保标签不被截断
          },
          dataZoom: [
            {
              type: 'slider',      // 滑动条型dataZoom（必须声明）
              height: 10,           // 滚动条高度
              bottom:16,
              show: salesData.length > minShowItems,          // 默认显示
              xAxisIndex: 0,       // 控制第一个xAxis
              zoomLock: true,        // 禁止缩放（仅滚动）
              start: 0,
              end: Math.min(100, (minShowItems / salesData.length) * 100), // 动态计算初始窗口
            }
          ],
          xAxis: {
            type: 'category',
            data: categories,
            axisLine: {
              lineStyle: {
                color: '#dadada', // X轴轴线颜色
              }
            },
            axisLabel: {
              color: '#818181',       // 字体颜色
              fontSize: 14,        // 字体大小
            },
            axisTick: {
              show: false,          // 显示刻度线
            },
          },
          yAxis: [
            {
              type: 'value',
              name: lineName,
              nameTextStyle:{
                color:'#898989'
              },
              position: 'left',
              axisLine: {
                lineStyle: {
                  color: '#dadada', // X轴轴线颜色
                }
              },
              axisLabel: {
                color: '#818181',       // 字体颜色
                fontSize: 10,        // 字体大小
              },
              splitLine: {
                show: true,                    // 需手动开启
                lineStyle: {
                  color: '#ebebeb',  // 半透明细线
                  width: 0.5
                }
              }
            }
          ],
          series: [
            {
              name:yName,
              type: 'bar',
              data: actualSales,
              yAxisIndex: 0,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                  { offset: 0, color: '#6084f2' },
                  { offset: 1, color: '#ffffff' }
                ])
              },
              barWidth:16,
              markLine:markLine,
            }
          ]
        };
        this.myChart.setOption(option);
        this.myChart.on('click', (params)=> {
          if(this.curIndex4 == 1 || this.curIndex4 == 2){
            this.topage('userSaleNumAnalysis')
          }else{
            // console.log(params)
            this.topage('goodsSaleNumAnalysis',params['name'])
          }

        })
      },

    }
  }
</script>


